import {Component, ViewChild, ElementRef, ChangeDetectorRef,} from '@angular/core';
import {Keyboard} from "@ionic-native/keyboard";
import {FileTransfer} from '@ionic-native/file-transfer';
import {
    AlertController,
    IonicPage,
    NavController,
    NavParams,
    ToastController,
    Platform,
    App,
    LoadingController,
    Content,
    ItemSliding,
    Select,
    Events
} from 'ionic-angular';
import $ from 'jquery'
import * as moment from 'moment';
import "rxjs/add/observable/of";

import {RecorderService} from '../../../services/recorder.service';
import {
    ScheduleItem,
    TimerItem,
    RepeatItem,
    NoticeItem,
    ScheduleStrResourceCh,
} from '../../../model/pages/schedule/schedule-add/schedule-add.model';
import {FileService} from '../../../services/native/file/file.service';
import {LocalStorageService} from "../../../services/native/local-storage/local-storage.service";
import {ScheduleAddProvider} from '../../../providers/schedule/schedule-add/schedule-add.provider';
import {ScheduleEndRepeatPage} from "../schedule-end-repeat/schedule-end-repeat";
import {ScheduleListProvider} from '../../../providers/schedule/schedule-list/schedule-list.provider';
import {ToastService} from '../../../services/common/toast.service';
import {LoadingService} from "../../../services/common/loading.service";
import {ThemeBrowserService} from "../../../services/native/theme-browser/theme-browser.service";
import {MessageBushService} from "../../../services/common/message-bush.service";

import {AdpActionSheetController} from '../../../components/common/adp-action-sheet/adp-action-sheet-controller';
import {TrackStatus} from "../../../model/pages/activity/roster-list/roster-list-item.model";

@IonicPage()
@Component({
    selector: 'page-schedule-add',
    templateUrl: 'schedule-add.html',
    providers: [
        FileTransfer,
        ScheduleAddProvider,
        RecorderService,
        FileService,
        LocalStorageService,
        ScheduleListProvider,
        ToastService,
        ThemeBrowserService,
        AdpActionSheetController
    ]
})
export class ScheduleAddPage {
    @ViewChild('remark') remarkElf: ElementRef;
    @ViewChild(Content) content: Content;
    @ViewChild('updateRule') updateRule: Select;
    @ViewChild('delRule') delRule: Select;

    moment = moment;
    // 用于全局控制弹窗的对象
    private alertObj;
    // 页面提示
    private curStrResource = ScheduleStrResourceCh;
    // 页面类型：1：新增，2：详情
    private pageType: number;
    // 是否为普通日程
    public editStatus: boolean = true;
    // 日程事项
    private data: ScheduleItem = new ScheduleItem();
    // 时间选择字符串
    private timerStr: TimerItem = new TimerItem();
    // 最小开始时间
    private minStartTime: string;
    // 最大开始时间
    private maxStartTime: string;
    // 最小结束时间
    private minEndTime: string;
    // 最大结束时间
    private maxEndTime: string;
    // 国际时间差值
    private differTime: number = 8 * 60 * 60 * 1000;
    // 显示的开始时间
    private startTime: string;
    // 显示的结束时间
    private endTime: string;
    // 重复
    private repeatItem = RepeatItem;
    // 提醒
    private noticeItem = NoticeItem;
    // 开始时间年度范围
    private startYearList: number[] = [];
    // 结束时间年度范围
    private endYearList: number[] = [];

    // 组件是否加载
    private audioStatus: boolean = true;
    // 录音按钮
    private audioBtn: number = 2;
    // 语音ID
    private id: string = '123';
    // 录音按钮显示/隐藏
    private enterStatus: boolean = false;
    // 语音时长
    private voiceLength: number = 0;
    // 语音文件
    private voiceFile: any = '';
    // 是否是新建的语音标记
    private isNewVoice: boolean = false;

    // 回填数据对象
    private createdSchedule: ScheduleItem = new ScheduleItem();
    // 当前编辑文字长度
    private editingLang: number;
    // 列表时间戳
    private firstUnix: number;
    // 时间组件文字填充
    private pickerOptions = {
        cssClass: 'schedule-add-picker',
    };

    // 上一条文字笔记
    private prevNote: string = '';
    endRepeat: any = '永不';//结束重复时间:永不 or UNIX时间戳
    prevFrequency: number;//进入详情时的重复类型
    updateRuleOption = [{value: 0, str: '仅针对此日程存储'}, {value: 1, str: '针对将来日程存储'}];
    // 删除提示弹框
    delRuleOption = [{value: 0, str: '仅删除此日程'}, {value: 1, str: '删除所有将来日程'}];

    // 视口中心区域高度
    private viewCenterHeight: number;
    // textarea高度
    private texareaHeight: number = 800;
    // texarea以上区域高度
    private itemsHeight: number;

    // 模拟滚动条滑块长度
    private slideHeight: number;
    // content是否滚动
    private scrollStatus: boolean;
    //从首页时入状态
    fromPage: string;
    // 请求状态
    requestStatus: boolean = true;

    constructor(public appCtrl: App,
                private platform: Platform,
                private alertCtrl: AlertController,
                private toastCtrl: ToastController,
                private navCtrl: NavController,
                private navParams: NavParams,
                private loadCtr: LoadingController,
                private ref: ChangeDetectorRef,
                private recorderService: RecorderService,
                private fileService: FileService,
                private scheduleAddProvider: ScheduleAddProvider,
                private scheduleListProvider: ScheduleListProvider,
                private keyboard: Keyboard,
                private toastService: ToastService,
                private loadingService: LoadingService,
                public themeBrowserService: ThemeBrowserService,
                private adpActionSheetController: AdpActionSheetController,
                private event:Events
                ) {
    }

    public backButtonHandle = () => this.backClickHandle();

    ionViewDidLoad() {
        const id = this.navParams.get('id');
        const date = this.navParams.get('date') * 1000;
        this.fromPage = this.navParams.get('fromPage');
        this.firstUnix = date;
        this.startYearList = this.scheduleAddProvider.getYearList(2010);
        this.endYearList = this.scheduleAddProvider.getYearList(this.moment(new Date()).year());
        if (!id) {
            this.data.remark = '';
            this.initScheduleNew(date);
        } else {
            this.initScheduleDetail(id, this.firstUnix);
        }
        setTimeout(() => {
            this.viewCenterHeight = this.content._fixedContent.nativeElement.clientHeight;
            this.itemsHeight = this.viewCenterHeight - window['innerWidth'] / 100 * 5 * 16;
        }, 200);
        //this.scroll();
    }

    ionViewDidEnter() {
        this.audioStatus = true;
    }

    setEndRepeat(endRepeat: string) {
        this.endRepeat = endRepeat;
    }

    /**
     * 显示结束重复的时间
     * @param endRepeat '永不'或者时间戳
     * @returns {string}
     */
    getEndRepeatTime(endRepeat) {
        if (endRepeat === '永不') {
            return '永不'
        } else {
            return moment(endRepeat * 1000).format('YYYY年MM月DD日')
        }
    }

    ionViewWillLeave() {
    }

    openEndRepeat(endTimeStr) {
        if (!this.editStatus) {
            return false
        }
        this.audioStatus = false;
        this.navCtrl.push('ScheduleEndRepeatPage', {endTime: endTimeStr, endRepeat: this.endRepeat})
    }

    // 新建页初始化数据
    initScheduleNew(date: number) {
        const startTime = this.scheduleAddProvider.timeFormat(date, true);
        const endTime = this.scheduleAddProvider.timeFormat(date + 60 * 60 * 1000, true);
        if (!startTime || !endTime) {
            return false;
        }
        this.data.startTime = new Date(startTime.showTime).getTime();
        this.timerStr.startTimeStr = startTime.ionTime;
        this.data.endTime = new Date(endTime.showTime).getTime();
        this.timerStr.endTimeStr = endTime.ionTime;
        this.data.frequency = 1;
        this.data.reminder = 1;
        this.editStatus = true;
        this.pageType = 1;
        this.maxEndTime = this.scheduleAddProvider.limitTimeRange(this.data.startTime).maxTime;
        this.editingLang = 0;
    }

    // 详情页初始化数据
    initScheduleDetail(id: string, date: number) {
        this.pageType = 2;
        let item = this.navParams.get('item');
        if (item != null) {
            this.getDetailData(item);
            return;
        }

        // p.groupId
        this.scheduleListProvider.getDayData(date / 1000).subscribe(res => {
            this.getDetailData(res.find(p => p.groupId == id));
        }, (error) => {
            console.log(error);
        });
    }

    getDetailData(res) {
        this.data = res;
        this.data.startTime = this.data.startTime * 1000;
        this.data.endTime = this.data.endTime * 1000;
        const isoTime = this.scheduleAddProvider.getISOString(this.data.startTime, this.data.endTime);
        this.timerStr.startTimeStr = isoTime.startTimeStr;
        this.timerStr.endTimeStr = isoTime.endTimeStr;
        if (this.data.voiceUrl) {
            this.isNewVoice = false;
            this.voiceFile = this.data.voiceUrl;
            this.voiceLength = this.data.voiceLength;
        }
        this.editStatus = !(this.data.type != 1);
        this.maxEndTime = this.scheduleAddProvider.limitTimeRange(this.data.startTime).maxTime;
        this.data.remark ? this.editingLang = this.data.remark.length : this.editingLang = 0;
        this.data.remark ? this.prevNote = this.data.remark : null;

        this.prevFrequency = res.frequency;
        if (res.until) {
            this.endRepeat = res.until
        } else {
            this.endRepeat = '永不'
        }
        this.goToOutlink();
    }

    // 开始时间选择
    onStartTimeChange() {
        this.data.startTime = new Date(this.timerStr.startTimeStr).getTime() - this.differTime;
        const startLimit = this.scheduleAddProvider.limitTimeRange(this.data.startTime);
        this.maxEndTime = startLimit.maxTime;
        this.data.endTime = startLimit.unixTime;
        this.timerStr.endTimeStr = startLimit.ionTime;
        this.endYearList = this.scheduleAddProvider.getYearList(this.moment(new Date(this.data.startTime)).year());
        this.ref.detectChanges();
    }

    // 结束时间选择
    onEndTimeChange() {
        this.data.endTime = new Date(this.timerStr.endTimeStr).getTime() - this.differTime;
        this.ref.detectChanges();
    }

    // 初始化日程重复选择项
    initFrequency() {
        let result = [];
        for (let f in this.repeatItem) {
            console.log(f);
            let obj = {};
            obj['text'] = this.repeatItem[f];
            obj['cssClass'] = this.data.frequency == Number(f) + 1 ? 'action-sheet-selected' : null;
            obj['handler'] = () => {
                this.data.frequency = Number(f) + 1;
            };
            result.push(obj)
        }
        return result
    }

    openActionFrequency(ev) {
        ev.stopPropagation();
        console.log('open');
        if (!this.editStatus) {
            return false
        }
        let btn = this.initFrequency();
        this.adpActionSheetController.create({
            title: '是否重复',
            cssClass: 'roster-action',
            buttons: btn
        }).present();
    }

    // 初始化日程提醒选择项
    initReminder() {
        let result = [];
        for (let f in this.noticeItem) {
            console.log(f);
            let obj = {};
            obj['text'] = this.noticeItem[f];
            obj['cssClass'] = this.data.reminder == Number(f) + 1 ? 'action-sheet-selected' : null;
            obj['handler'] = () => {
                this.data.reminder = Number(f) + 1;
            };
            result.push(obj)
        }
        return result
    }

    openActionReminder(ev) {
        ev.stopPropagation();
        if (!this.editStatus) {
            return false
        }
        let btn = this.initReminder();
        this.adpActionSheetController.create({
            title: '提醒',
            cssClass: 'roster-action',
            buttons: btn
        }).present();
    }

    // 页面返回
    backClickHandle() {
        this.audioStatus = false;
        this.voiceFile = '';
        this.navCtrl.pop();
    }

    // 开关录音按钮
    voiceChange() {
        this.enterStatus = !this.enterStatus;
    }

    // 录音成功
    recordSuccess($event) {
        this.voiceFile = $event.voiceUrl;
        this.voiceLength = $event.voiceLength;
        this.isNewVoice = true;
    }

    // 删除语音
    deleteVoice(e, itemSliding: ItemSliding) {
        e.stopPropagation();
        e.preventDefault();
        this.showConfirm('确认删除？',
            () => {
                this.voiceFile = '';
                this.voiceLength = 0;
                this.isNewVoice = false;
            },
            () => {
                itemSliding.close();
            });
    }

    /**
     * 保存语音文件
     */
    saveVoice(request) {
        let $this = this;
        if (!this.isNewVoice) {
            this.loadingService.showLoading();
            request($this);
            return false;
        }
        if (this.voiceFile) {
            this.loadingService.showLoading();
            this.fileService.saveFile(this.recorderService.getFilePath(this.voiceFile),
                this.voiceFile,
                this.recorderService.getMimeType()).subscribe(result => {
                this.voiceFile = result;
                request($this);
            }, err => {
                this.toastService.showToast('语音上传失败');
                this.loadingService.dismissLoading();
            });
        }
    }

    //  新建日程保存
    saveHandler() {
        const checkResult = this.scheduleAddProvider.checkFormData(this.data);
        if (checkResult) {
            this.toastService.showToast(checkResult);
            return false;
        }
        if (this.data.endTime < this.data.startTime) {
            this.toastService.showToast('结束时间不能小于开始时间');
            return false;
        }
        if (this.getDaysDiff(this.data.startTime, this.data.endTime) > 4 && this.data.frequency != 1) {
            this.toastService.showToast('日程跨天数范围不能超过五天');
            return false;
        }
        this.saveVoice(this.addScheduleRequest);
    }

    // 添加日程请求
    addScheduleRequest($this) {
        if (!$this.requestStatus) {
            return false
        } else {
            $this.requestStatus = false;
        }
        $this.data.type = 1;
        $this.requestBefore();
        $this.voiceFile ? $this.voiceFile = 'string' : null;
        $this.scheduleAddProvider.postNewScheduleItem($this.data).subscribe((res) => {
            MessageBushService.setMessage(MessageBushService.keys.indexSheduleSaveSuccess, '1');
            $this.requestStatus = true;
            if (res.name) {
                $this.loadingService.dismissLoading();
                $this.audioStatus = false;
                $this.navCtrl.pop().then(() => {
                    const viewControllers = $this.appCtrl.getActiveNavs()[0]._views;
                    const len = viewControllers.length;
                    const popView = viewControllers[len - 1];
                    if (popView.id === 'ScheduleListPage') {
                        popView.instance.queryData();
                    }
                });
            }
        }, error => {
            $this.requestStatus = true;
            $this.voiceFile = $this.data.voiceUrl;
            if (error.status == 500) {$this.toastService.showToast('日程保存失败')}
            $this.loadingService.dismissLoading();
        })
    }

    // 编辑日程保存
    editHandler() {
        const checkResult = this.scheduleAddProvider.checkFormData(this.data);
        if (checkResult) {
            this.toastService.showToast(checkResult);
            return false;
        }
        if (this.data.endTime < this.data.startTime) {
            this.toastService.showToast('结束时间不能小于开始时间');
            return false;
        }
        if (this.getDaysDiff(this.data.startTime, this.data.endTime) > 4 && this.data.frequency != 1) {
            this.toastService.showToast('日程跨天数范围不能超过五天');
            return false;
        }
        this.choiceUpdateRule();
    }

    // 计算开始时间结束时间的天数差值
    getDaysDiff(start, end) {
        let from = moment(start).format('YYYY-MM-DD');
        let to = moment(end).format('YYYY-MM-DD');
        console.log(moment(new Date(to)).diff(moment(new Date(from)), 'days'));
        return moment(new Date(to)).diff(moment(new Date(from)), 'days')
    }

    //选择修改方式：当前、以后
    choiceUpdateRule() {
        this.data.appointDay = this.firstUnix / 1000;//修改时必传当前修改的日程所在日期
        if (this.data.frequency !== this.prevFrequency && this.prevFrequency === 1) {
            //重复状态改变，且初始重复=永不的,弹出修改方式提示，且只有一个选项
            this.data.updateRule = 1;
            return this.saveVoice(this.editRequest);
        } else if ((this.data.frequency !== this.prevFrequency && this.prevFrequency !== 1)) {
            //重复状态改变，且初始重复!=永不的，弹出修改方式提示，且只有一个选项
            this.updateRuleOption = [{value: 1, str: '针对将来日程存储'}];
            this.ref.detectChanges();
            this.updateRule.open();
            return;
        } else if ((this.data.frequency === this.prevFrequency && this.prevFrequency !== 1)) {
            //重复状态不变，且初始重复!=永不的，弹出修改方式提示，自己选择
            this.updateRule.open();
            return;
        } else {
            return this.saveVoice(this.editRequest);
        }

    }

    // 选择修改方式
    selUpdateRule() {
        this.saveVoice(this.editRequest);
    }

    // 编辑日程请求
    editRequest($this) {
        if (!$this.requestStatus) {
            return false
        } else {
            $this.requestStatus = false;
        }
        $this.data.voiceUrl && !$this.voiceFile ? $this.deleteVoiceSource($this.data.voiceUrl) : null;
        $this.requestBefore();
        $this.voiceFile ? $this.voiceFile = 'string' : null;
        $this.scheduleAddProvider.updateScheduleItem($this.data.id, $this.data).subscribe((res) => {
            $this.requestStatus = true;
            MessageBushService.setMessage(MessageBushService.keys.indexSheduleSaveSuccess, '1');

            $this.loadingService.dismissLoading();
            $this.audioStatus = false;
            $this.navCtrl.pop().then(() => {
                const viewControllers = $this.appCtrl.getActiveNavs()[0]._views;
                const len = viewControllers.length;
                const popView = viewControllers[len - 1];
                if (popView.id === 'ScheduleListPage') {
                    popView.instance.queryData();
                }
            });
        }, error => {
            $this.requestStatus = true;
            $this.voiceFile = $this.data.voiceUrl;
            $this.loadingService.dismissLoading();
        })
    }

    // 请求前数据处理
    requestBefore() {
        if (this.endRepeat === '永不') {
            this.data.until = null
        } else {
            //结束重复时分取日程结束时间的时分
            let hours = this.moment(this.timerStr.endTimeStr).utc().hour();
            let minute = this.moment(this.timerStr.endTimeStr).minute();
            //结束重复年月日结束重复自己的年月日
            let year = this.moment(new Date(this.endRepeat * 1000)).year();
            let month = this.moment(new Date(this.endRepeat * 1000)).month();
            let date = this.moment(new Date(this.endRepeat * 1000)).date();

            this.data.until = this.moment([year, month, date, hours, minute]).unix();
        }

        this.data.voiceUrl = this.voiceFile;
        this.data.voiceLength = this.voiceLength;
        if (String(this.data.startTime).length == 13 || String(this.data.startTime).length == 12) {
            this.data.startTime = Math.floor(this.data.startTime / 1000);
            this.data.endTime = Math.floor(this.data.endTime / 1000);
        }
    }

    // 删除日程
    deleteSchedule() {
        this.data.appointDay = this.firstUnix / 1000;//修改时必传当前修改的日程所在日期
        if (this.prevFrequency == 1) {
            // 为永不时弹出提示
            this.showConfirm('确认删除？',
                () => {
                    //初始重复=永不的删除不弹出提示
                    this.data.delRule = 0;
                    this.deleteRequest(this.data.id);
                    this.data.voiceUrl ? this.deleteVoiceSource(this.data.voiceUrl) : null;
                },
                () => {
                });
        } else {
            //初始重复!=永不的删除弹出提示
            this.delRule.open();
            return;
        }
    }

    // 删除语音文件
    deleteVoiceSource(fileId) {
        this.fileService.deleteFile(fileId).subscribe((res) => {
            console.log(res)
        })
    }

    // 删除方式
    selDelRule() {
        this.deleteRequest(this.data.id);
    }

    // 删除日程请求
    deleteRequest(id: number) {
        this.scheduleAddProvider.deleteScheduleItem(id, this.data.appointDay, this.data.delRule).subscribe((res) => {
            MessageBushService.setMessage(MessageBushService.keys.indexSheduleSaveSuccess, '1');
            this.audioStatus = false;
            this.voiceFile = '';
            this.navCtrl.pop().then(() => {
                const viewControllers = this.appCtrl.getActiveNavs()[0]._views;
                const len = viewControllers.length;
                const popView = viewControllers[len - 1];
                if (popView.id === 'ScheduleListPage') {
                    popView.instance.queryData();
                }
            });
        }, error => {
            this.voiceFile = this.data.voiceUrl;
            if (error.status == 500) {this.toastService.showToast('删除失败')}
        })
    }

    /**
     * 确认框
     *
     * @private
     * @param {any} msg 询问的消息
     * @param {any} okCallback 用户点击确定后的回调
     * @param {any} cancelCallback 用户点击取消后的回调
     * @memberof ScheduleAddPage
     */
    showConfirm(msg, okCallback, cancelCallback) {
        if (this.alertObj) return;
        this.alertObj = this.alertCtrl.create({
            enableBackdropDismiss: false,
            message: msg,
            buttons: [{
                text: this.curStrResource.StrCancel,
                handler: cancelCallback
            }, {
                text: this.curStrResource.StrOk,
                handler: okCallback
            }]
        });
        this.alertObj.onDidDismiss(() => this.alertObj = null);
        this.alertObj.present();
    }

    // 备注聚焦调整textarea最大高度
    remarkCursor(e) {
        let top = e.target.offsetParent.offsetParent.offsetTop - window['innerWidth'] / 100 * 16 * 2;
        this.content.scrollTo(0, top);
        let $this = this;
        if (this.platform.is('ios')) {
            let val = this.data.remark;
            //this.data.remark = ' ';
            setTimeout(() => {
                this.data.remark = val;
                e.target.click();
            }, 50);
        }
        window.addEventListener('native.keyboardshow', function (e) {
            //e.keyboardHeight 表示软件盘显示的时候的高度
            console.log(e['keyboardHeight']);
            $this.texareaHeight = $this.viewCenterHeight - e['keyboardHeight'] - ($this.itemsHeight - e['keyboardHeight']) - window['innerWidth'] / 100 * 40;
        });
    }

    // 备注框失焦点
    lostTarget($event) {
        this.scrollStatus = false;
    }

    // 填写备注
    fillRemark($event, flag) {
        console.log($event);
        /*if ($event.data && $event.data.match(/(\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]|\ud83d[\ude80-\udeff])/g)) {
            this.data.remark = this.data.remark.substr(0, this.data.remark.length - 1);
            this.editingLang = this.data.remark.length;
        }*/
        setTimeout(() => {
            if (this.prevNote.length >= 200 && this.data.remark.length >= 200) {
                this.data.remark = this.prevNote.substr(0, 200);
            } else {
                this.data.remark = this.data.remark.substr(0, 200);
                this.prevNote = JSON.parse(JSON.stringify(this.data.remark));
            }
            this.editingLang = this.data.remark.length;
        }, 300);
    }

    // 备注外链到浏览器平台
    goToOutlink() {
        let $this = this;
        setTimeout(() => {
            $('.system-innerContent a').on("click", function (e) {
                e.stopPropagation();
                e.preventDefault();
                if (e.target['href']) {
                    $this.themeBrowserService.openBrowser(e.target['href']);
                }
            })
        }, 200)
    }

}

